package com.tk.exam.interceptor;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class RequestInterceptor {

    // 对以下com.sinochem.yunlian.upm.api.web类中的所有方法进行切入
    @Pointcut("execution(* com.tk.exam.web..*.*(..))")
    private void method() {
    }

    @Before("method()")
    public void doBefore(JoinPoint joinPoint) {

    }

    @Around("method()")
    public Object doAfter(ProceedingJoinPoint joinPoint) throws Throwable {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");

        log.info("请求链接={};请求方式={};IP={};请求参数={};token={};", request.getRequestURL(), request.getMethod(), request.getRemoteAddr(), joinPoint.getArgs(), token);
        log.info("HttpAspect doAfter Running : " + System.currentTimeMillis());
        long start = System.currentTimeMillis();
        Object obj = joinPoint.proceed();
        if (obj instanceof ResponseEntity) {
            log.info("响应参数={};url={}", obj, request.getRequestURL());
        } else {
            log.info("响应参数={};url={}", JSON.toJSONString(obj), request.getRequestURL());
        }
        log.info("耗时 : " + (System.currentTimeMillis() - start) + "ms");
        return obj;
    }

}
